package com.lzy.example.utils;


import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.property.TabAlignment;
import com.itextpdf.layout.property.TextAlignment;

import com.itextpdf.text.pdf.BaseFont;
import com.lzy.example.entity.WenShuInfo;
import org.junit.Test;
import org.springframework.util.ResourceUtils;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

// 参考网址：https://blog.csdn.net/tzxylao/article/details/106486009
//https://www.cnblogs.com/matrix-zhu/p/6305944.html
//https://www.cnblogs.com/top5/archive/2012/02/21/2362380.html
// text 居中对齐https://www.thinbug.com/q/52259137

public class wenanPdfUtil {

    public  final String DEST = "results/chapter02/star_wars.pdf";

    public void createWenAn(WenShuInfo wenShuInfo, String filePath, float contentFontSize) {
        PdfWriter writer = null;
        PdfDocument pdf = null;
        Document document = null;
        try {
            //初始化 PDF Writer
            writer = new PdfWriter(filePath);
            //加载模版-方法1
              //项目路径获取方法1
            //String realPath = request.getSession().getServletContext().getRealPath("/");//项目路径
            //项目路径获取方法2——模版文件所在项目位置：E:/work/demo-study/templates/pdf/wenanTop.pdf
            String templatePath = ResourceUtils.getURL("classpath:templates/pdf/wenanTop.pdf").getPath();
            PdfReader reader = new PdfReader(new File(templatePath));
            //加载模版-方法2
//            PdfReader reader = new PdfReader(new File(getPdfTemplatesDir(),"wenanTop.pdf"));
            //初始化 PDF Document
            pdf = new PdfDocument(reader,writer);
            //初始化 Document
            document = new Document(pdf, PageSize.A4);
            document.setSplitCharacters(new ChineseSplitCharater());
//            document.setSplitCharacters();
            document.setTopMargin(145);

            //处理中文问题
            PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            // itext5加载字体方法
//            BaseFont bfComic4 = BaseFont.createFont("c:\\windows\\fonts\\SIMFANG.TTF",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            // itext7加载字体
            PdfFont f3 = PdfFontFactory.createFont("C:/Windows/Fonts/simhei.ttf", PdfEncodings.IDENTITY_H,true);
            String fontsPath = ResourceUtils.getURL("classpath:templates/fonts").getPath();

//            String fontPath = request.getSession().getServletContext().getRealPath("/");
            System.out.println(fontsPath);
            PdfFont fangSong = PdfFontFactory.createFont(fontsPath+"/simfang.ttf", PdfEncodings.IDENTITY_H,false);
            PdfFont song = PdfFontFactory.createFont(fontsPath+"/songTi.ttf", PdfEncodings.IDENTITY_H,true);
            //绘制页面内容
            Div div = new Div();
            div.setPadding(45f);
//            Div titleDiv = new Div();
//            //绘制标题
//            Paragraph pTop = new Paragraph("中山市公安局经济犯罪侦查支队");
//            pTop.setFontSize(30).setBold().setTextAlignment(TextAlignment.CENTER).setFont(font);
//            //绘制文书类型
//            Paragraph pType = new Paragraph("外协案件交办通知书");
//            pType.setFontSize(20).setBold().setTextAlignment(TextAlignment.CENTER).setFont(font);
//            titleDiv.add(pTop).add(pType);
            //绘制主体
            Div bodyDiv = new Div();
            Div contentDiv = new Div();
            Paragraph pTitle = new Paragraph("外协案件交办通知书").setTextAlignment(TextAlignment.CENTER).setBold().setFontSize(21.95f).setFont(song).setPaddingBottom(20);
            Paragraph pContent = new Paragraph().setFontSize(contentFontSize).setFont(fangSong);  //.setFirstLineIndent(28)
            Text xiebanDept = new Text(wenShuInfo.getXiebanDept()+"：\n");
            Text dept = new Text(wenShuInfo.getDept()).setUnderline(0.2f, -2f);
            Text caseName = new Text(wenShuInfo.getCaseName()).setUnderline(0.2f, -2f);
            Text xiebanNeed = new Text(wenShuInfo.getXiebanNeed()).setUnderline(0.2f, -2f);
            Text other = new Text("请求协作。经我支队审查，该协作事项法律文书和手续完备，符合协作要求，请予以配合协助办理以下事项：");
            //add(new Tab()).addTabStops(new TabStop(28, TabAlignment.LEFT))实现首行缩进两个字，与setFirstLineIndent(28)效果一致
            pContent.add(xiebanDept).add(new Tab()).addTabStops(new TabStop(28, TabAlignment.LEFT)).add(dept).add("现因办理：").add(caseName).add(other).add(xiebanNeed);
            contentDiv.add(pTitle).add(pContent);



            Div endDiv = new Div().setPaddingRight(30).setKeepTogether(true);
            //联系人
            Paragraph pContact = new Paragraph().setTextAlignment(TextAlignment.RIGHT).setFontSize(contentFontSize).setFont(fangSong).setPaddingTop(30);
            Text contact = new Text(wenShuInfo.getContact()).setUnderline();
            Text phone = new Text(wenShuInfo.getPhone()).setUnderline();
            pContact.add("联系人：").add(contact).add("    电话：").add(phone);
            //落款
            Paragraph pLuokuan = new Paragraph().setTextAlignment(TextAlignment.RIGHT).setFontSize(contentFontSize).setFont(fangSong).setPaddingTop(60);
            Text luokuanDept = new Text("中山市公安局经侦支队四大队\n");
            Text date = new Text(dateTransform(new Date()));
            pLuokuan.add(luokuanDept).add(date).add(new Tab()).addTabStops(new TabStop(40, TabAlignment.RIGHT));
            endDiv.add(pContact).add(pLuokuan);



            bodyDiv.add(contentDiv).add(endDiv);
            div.add(bodyDiv);
//            div.add(pTitle).add(pType).add(pContent);
            document.add(div);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
          if (document != null) {
              document.close();
          }
          if (pdf != null) {
              pdf.close();
          }
          if (writer != null) {
              try {
                  writer.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
        }

    }

    protected String dateTransform(Date currentTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年M月d日");
        String date = dateFormat.format(currentTime);
        return date;
    }


    public static void main(String[] args) {
        WenShuInfo wenShuInfo = new WenShuInfo();
        wenShuInfo.setXiebanDept("古镇分局");
        wenShuInfo.setDept("河南省平顶山矿工路公安分局");
        wenShuInfo.setCaseName("2020.12.30平顶山呼衰强等人非法经营案");
        wenShuInfo.setXiebanNeed("抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,抓捕1名嫌疑人，姓名：刘亚辉，身份证：12345678910,");
        wenShuInfo.setContact("米田共");
        wenShuInfo.setPhone("123456789");
        wenanPdfUtil wenanUtil = new wenanPdfUtil();
//        wenanUtil.createWenAn(wenShuInfo, "E:/wenanPdf000.pdf", 20);
        String str = "一a";
        int length = 0;
        try {
            length = str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(length);
        System.out.println(3/2);
//        createWenAn(wenShuInfo, "E:/wenanPdf000.pdf", 20);
    }

    protected File getTemporaryDir() {
        try {
            return ResourceUtils.getFile("temporary");
        } catch (FileNotFoundException e) {
            return new File(".");
        }
    }

    /**
     * pdf模版文件夹
     * @return
     * @throws FileNotFoundException
     */
    protected File getTemplatesDir() throws FileNotFoundException {
        return ResourceUtils.getFile("templates");
    }

    /**
     * pdf模版文件夹
     * @return
     * @throws FileNotFoundException
     */
    protected File getPdfTemplatesDir() throws FileNotFoundException {
        return new File(getTemplatesDir(), "pdf");
    }

    /**
     * 仿宋字体
     * @return
     */
    protected String getFangSongPath() {
        try {
            return ResourceUtils.getFile("templates/fonts/FSZT.ttf").getPath();
        } catch (IOException e) {
            throw new RuntimeException("生成pdf出错，字体找不到!");
        }
    }



}
